package com.steven.tool;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:heshuang@cqyyt.com">heshuang</a>
 * @version 1.0
 * @date 2019/8/20 17:14
 * @desc
 */
public class Build {
    public final static  List<String> LIST_FILES=new ArrayList<>();
    //物理路径
    public final static String OGIS_PATH = "F:\\WorkSpace\\YYT\\广东省\\惠州市第一人民医院\\OGISSystem\\ogis-web\\target\\ogis-web";
    //是否打包底层配置js he css
    public final static boolean IS_DING = false;


    public static void main(String args[]) {
        String OGIS_WAR= OGIS_PATH+".war";
        String TAR_PATH= OGIS_PATH+".zip";
        readFile();
        delFile(OGIS_PATH);
        delFolder(OGIS_PATH);
        try {
            packToolFiles(OGIS_PATH,TAR_PATH);
            Thread.sleep(2000L);
            upzipFile(new File(OGIS_WAR),OGIS_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void readFile() {
        LIST_FILES.add("/WEB-INF/lib/ogis-common-1.0.0.jar");
        LIST_FILES.add("/WEB-INF/lib/ogis-dao-1.0.0.jar");
        LIST_FILES.add("/WEB-INF/lib/ogis-entity-1.0.0.jar");
        LIST_FILES.add("/WEB-INF/lib/ogis-service-1.0.0.jar");
        LIST_FILES.add("/WEB-INF/lib/ogis-business-1.0.0.jar");
        LIST_FILES.add("/WEB-INF/lib/ogis-framework-1.0.0.jar");
        LIST_FILES.add("ogis-design-common-1.0.1-SNAPSHOT.jar");
        LIST_FILES.add("ogis-design-dao-1.0.1-SNAPSHOT.jar");
        LIST_FILES.add("ogis-design-entity-1.0.1-SNAPSHOT.jar");
        LIST_FILES.add("ogis-design-security-gen-1.0.1-SNAPSHOT.jar");
        LIST_FILES.add("ogis-design-security-license-1.0.1-SNAPSHOT.jar");
        LIST_FILES.add("ogis-design-service-1.0.1-SNAPSHOT.jar");
//        File file = new File(OGIS_FILE_PATH);
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("update.txt");
            InputStreamReader inputReader = new InputStreamReader(resourceAsStream);
            BufferedReader bf = new BufferedReader(inputReader);
            // 按行读取字符串
            String str;
            while ((str = bf.readLine()) != null) {
                System.out.println(str);
                if(StringUtils.isEmpty(str)){
                    continue;
                }
                String[] split;
                split = str.split("/src");
                String path =split[1];
                if(path.indexOf(".java")>=0){
                    path=path.replace(".java",".class");
                }

                //controller
                path=path.replace("/main/java/","/WEB-INF/classes/");
                //配置文件
                path=path.replace("/main/resources/","/WEB-INF/classes/");
                //jsp页面
                path=path.replace("/main/webapp/WEB-INF/views/","/WEB-INF/views/");
                //静态资源
                path=path.replace("/main/webapp/resources/","/resources/");
                //模板
                path=path.replace("/main/webapp/template/","/template/");
                LIST_FILES.add(path);
            }
            bf.close();
            inputReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除文件
     * @param path
     */
    public static void delFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length > 0) {
                for (File file2 : files) {
                    String absolutePath = file2.getAbsolutePath();
                    if (file2.isDirectory()) {
                        delFile(absolutePath);
                    } else {
                        String real_path =absolutePath.replaceAll("\\\\", "/");

                        if(real_path.indexOf("/design") >= 0 && IS_DING){
                            continue;
                        }
                        List<String> collect = LIST_FILES.stream().filter(ccc -> real_path.indexOf(ccc) >= 0).collect(Collectors.toList());
                        if(collect==null ||collect.size()==0){
                            file2.delete();
                        }
                    }
                }
            }
        }
    }
    /**
     * 删除空文件夹
     * @param path
     */
    public static void delFolder(String path) {
        File dir = new File(path);
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (file.list().length == 0) {
                    file.delete();
                } else {// else将继续递归
                    delFolder(file.getPath());
                    if (file.list().length == 0) {
                        file.delete();
                    }
                }
            }
        }
    }




    public static void packToolFiles(String dirpath, String zipFilePath)
            throws Exception {

        OutputStream out = null;
        BufferedOutputStream bos = null;
        ZipArchiveOutputStream zaos = null;
        File zipFile = new File(zipFilePath);
        if (!zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }
        zipFile.delete();
        try {
            out = new FileOutputStream(zipFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bos = new BufferedOutputStream(out);
        zaos = new ZipArchiveOutputStream(bos);
        zaos.setEncoding("GBK");
        packToolFiles(zaos, dirpath, "");
        zaos.flush();
        zaos.close();
        bos.flush();
        bos.close();
        out.flush();
        out.close();
    }

    /**
     *
     * 把一个目录打包到一个指定的zip文件中
     *
     * @param dirpath
     *            目录绝对地址
     *
     * @param pathName
     *            zip文件抽象地址
     */

    private static void packToolFiles(ZipArchiveOutputStream zaos,
                                      String dirpath, String pathName) throws FileNotFoundException,
            IOException {
        ByteArrayOutputStream tempbaos = new ByteArrayOutputStream();
        BufferedOutputStream tempbos = new BufferedOutputStream(tempbaos);
        File dir = new File(dirpath);
        // 返回此绝对路径下的文件
        File[] files = dir.listFiles();
        if (files == null || files.length < 1) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            // 判断此文件是否是一个文件夹
            if (files[i].isDirectory()) {
                packToolFiles(zaos, files[i].getAbsolutePath(), pathName
                        + files[i].getName() + File.separator);
            } else {
                zaos.putArchiveEntry(new ZipArchiveEntry(pathName
                        + files[i].getName()));
                IOUtils.copy(new FileInputStream(files[i].getAbsolutePath()),
                        zaos);
                zaos.closeArchiveEntry();
            }
        }
        tempbaos.flush();
        tempbaos.close();
        tempbos.flush();
        tempbos.close();
    }


    public static List<File> upzipFile(File zipFile, String descDir) throws IOException {
        //删除旧包
        deleteALL(new File(OGIS_PATH));
        List<File> list = new ArrayList<>();
        // 防止文件名中有中文时出错
        System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));
        if (!zipFile.exists()) {
            throw new RuntimeException("解压失败，文件 " + zipFile + " 不存在!");
        }
        ZipFile zFile =  null;
        InputStream in = null;
        OutputStream out = null;
        try {
            zFile = new ZipFile(zipFile);
            for (Enumeration entries = zFile.getEntries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                File file = new File(descDir + File.separator + entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    File parent = file.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    in = zFile.getInputStream(entry);
                    out = new FileOutputStream(file);
                    IOUtils.copy(in, out);
                    out.flush();
                    in.close();
                    list.add(file);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            zFile.close();
            in.close();
            out.close();
        }
        return list;
    }


    public static void deleteALL(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //打印文件名
            String name = file.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                deleteALL(f);
            } else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }



}